<template>
  <transition name="todo" appear>
    <div class="todo-item">
      <label>
        <span>
          <t-checkbox :checked="todo.done" @change="handleCheck(todo.id)">&nbsp;&nbsp;
            <span v-show="!todo.isEdit" class="todo-title">{{todo.title}}</span>
            <input
                type="text"
                v-show="todo.isEdit"
                :value="todo.title"
                @blur="handleBlur(todo,$event)"
                ref="inputTitle"
                class="change-input"
            >
          </t-checkbox>
        </span>

      </label>
      <div class="controller">
        <el-button
            type="primary"
            icon="el-icon-edit"
            :circle="true" :plain="true" size="mini"
            v-show="!todo.isEdit"
            @click="handleEdit(todo)"></el-button>
        <el-button
            type="danger"
            icon="el-icon-delete"
            :circle="true" :plain="true" size="mini"
            @click="handleDelete(todo.id)"></el-button>
      </div>
    </div>
  </transition>
</template>

<script>
export default {
  name: "todo-item",
  props:['todo'],
  methods:{
    //勾选、取消
    handleCheck(id){
      //通知APP组件将对应的todo对象的done取反
      this.$bus.$emit('checkTodo',id)
    },
    //删除
    handleDelete(id){
      this.$confirm("确认删除吗？").then(() => {
        this.$bus.$emit('deleteTodo',id)
      })
    },
    //编辑
    handleEdit(todo){
      if(todo.hasOwnProperty('isEdit')){
        todo.isEdit = true
      }else {
        this.$set(todo, 'isEdit', true)
      }
      //不能直接写，顺序执行问题
      //this.$refs.inputTitle.focus()
      this.$nextTick(function (){
        this.$refs.inputTitle.focus()
      })
    },
    //失去焦点后操作
    handleBlur(todo,e){
      todo.isEdit = false
      if(!e.target.value.trim()) return alert("输入不能为空！")
      this.$bus.$emit('updateTodo',todo.id,e.target.value)
    }
  }
}
</script>

<style scoped>
.todo-item {
  margin: 5px auto auto;
  width: 564px;
  height: 37px;
  line-height: 37px;
  transition: background-color 100ms;
  transition-timing-function: ease-in-out;
  border-radius: 9px;
}
.todo-item:hover {
  background: rgba(238,250,255,0.5);
}
.todo-item label {
  margin-left: 5px;
  line-height: 41px;
  cursor: pointer;
}
.todo-item label span {
  margin-top: 5px;
}
.todo-item .controller {
  float: right;
  opacity: 0.0;
  margin-right: 10px;
  line-height: 2;
  transition: opacity 100ms;
  transition-timing-function: ease-in-out;
}
.todo-item:hover .controller {
  opacity: 1;
}
.todo-title {
  font-size: 14px;
  color: #4b4b4b;
}
.change-input {
  width: 300px;
  height: 20px;
  font-size: 12px;
  border-radius: 6px;
  padding: 2px 12px;
  border: none;
  outline: none;
  box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6);
}
.change-input:focus {
  outline: none;
  border-color: rgba(82, 168, 236, 0.8);
}

</style>
